package sso.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.access.AccessDeniedHandler;
import sso.util.WebUtils;

import java.util.HashMap;
import java.util.Map;
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //1.关闭跨域攻击
        http.csrf().disable();
        //设置拒绝处理器（不允许访问资源时，反馈信息 ）
        http.exceptionHandling()
        .accessDeniedHandler(accessDeniedHandler());
        //资源访问(不进行认证，认正是认证服务器)
        http.authorizeRequests().anyRequest().permitAll();
    }
    @Bean
    public AccessDeniedHandler accessDeniedHandler(){
        return (
                    httpServletRequest,
                    httpServletResponse,
                    e) -> {
                //1。构建一个响应信息
            Map<String,Object> map=new HashMap<>();
            map.put("state", 403);
            map.put("message","权限不足");
            WebUtils.writeJsonToClient(httpServletResponse,map);

            };
    }
}
